﻿using System;
using System.IO;

////////////////////////
//  Classe du paquet  //
////////////////////////

namespace Strom.Core.Network
{
    public class Packet
    {
        public byte ID { get; private set; }
        public int DatasLenght { get; private set; }
        public byte[] Datas { get; private set; }
        private const int HeaderLenght = 5;
        public PacketReader Reader { get; set; }

        // Configuration du paquet (ID et longueur)
        public Packet(byte id, int datasLenght)
        {
            ID = id;
            DatasLenght = datasLenght;
        }

        // Configuration des données du paquet
        public void SetDatas(byte[] datas)
        {
            Datas = datas;
            DatasLenght = Datas.Length; 
            Reader = new PacketReader(Datas);
        }

        // Créé un paquet à partir d'un tableau entête
        public static Packet FromHeaderArray(byte[] header)
        {
            byte id = header[0];
            int datasLenght = BitConverter.ToInt32(header, 1);

            return new Packet(id, datasLenght);
        }

        // Retourne le paquet COMPLET
        public byte[] GetFullPacket()
        {
            if(Datas == null)
                return new byte[0];

            var array = new byte[HeaderLenght + DatasLenght];
            array[0] = ID;
            Array.Copy(BitConverter.GetBytes(DatasLenght), 0, array, 1, 4);
            Array.Copy(Datas, 0, array, HeaderLenght, Datas.Length);

            return array;
        }

        public static byte GetHeaderLenght()
        {
            return HeaderLenght;
        }

        // représentation en string des données du packet
        public override string ToString()
        {
            return string.Format("[ID={0},Lenght={1}]", ID, DatasLenght);
        }
    }
}
